use loco_rs::prelude::*;
use sea_orm::DeleteResult;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub use super::_entities::sea_orm_active_enums::Based;
pub use super::_entities::tax_rules::{self, ActiveModel, Entity, Model};

#[derive(Debug, Deserialize, Serialize)]
pub struct CreateParams {
    pub tax_class_id: String,
    pub tax_rate_id: String,
    pub based: Based,
    pub priority: i32,
}

#[derive(Debug, Validate, Deserialize)]
pub struct Validator {
    #[validate(length(min = 1, message = "Tax Class ID must not be empty."))]
    pub tax_class_id: String,
    #[validate(length(min = 1, message = "Tax Rate ID must not be empty."))]
    pub tax_rate_id: String,
}

impl Validatable for ActiveModel {
    fn validator(&self) -> Box<dyn Validate> {
        Box::new(Validator {
            tax_class_id: self.tax_class_id.as_ref().to_owned(),
            tax_rate_id: self.tax_rate_id.as_ref().to_owned(),
        })
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for super::_entities::tax_rules::ActiveModel {
    async fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        self.validate()?;
        if insert {
            let mut this = self;
            this.id = ActiveValue::Set(Uuid::new_v4().to_string());
            Ok(this)
        } else {
            Ok(self)
        }
    }
}

impl Model {
    /// finds a tax rule by the provided id
    ///
    /// # Errors
    ///
    /// When could not find tax rule or DB query error
    pub async fn find_by_id(db: &DatabaseConnection, id: &str) -> ModelResult<Self> {
        let tax_rule = tax_rules::Entity::find()
            .filter(
                model::query::condition()
                    .eq(tax_rules::Column::Id, id)
                    .build(),
            )
            .one(db)
            .await?;
        tax_rule.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// finds tax rules by the provided tax class id
    ///
    /// # Errors
    ///
    /// When could not find tax rules or DB query error
    pub async fn find_by_tax_class_id(
        db: &DatabaseConnection,
        tax_class_id: &str,
    ) -> ModelResult<Vec<Self>> {
        let tax_rules = tax_rules::Entity::find()
            .filter(
                model::query::condition()
                    .eq(tax_rules::Column::TaxClassId, tax_class_id)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(tax_rules)
    }

    /// finds tax rules by the provided tax rate id
    ///
    /// # Errors
    ///
    /// When could not find tax rules or DB query error
    pub async fn find_by_tax_rate_id(
        db: &DatabaseConnection,
        tax_rate_id: &str,
    ) -> ModelResult<Vec<Self>> {
        let tax_rules = tax_rules::Entity::find()
            .filter(
                model::query::condition()
                    .eq(tax_rules::Column::TaxRateId, tax_rate_id)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(tax_rules)
    }

    /// Asynchronously creates a tax rule and saves it to the database.
    ///
    /// # Errors
    ///
    /// When could not save the tax rule into the DB
    pub async fn create(db: &DatabaseConnection, params: &CreateParams) -> ModelResult<Self> {
        let tax_rule = tax_rules::ActiveModel {
            tax_class_id: ActiveValue::set(params.tax_class_id.to_string()),
            tax_rate_id: ActiveValue::set(params.tax_rate_id.to_string()),
            based: ActiveValue::set(params.based.clone()),
            priority: ActiveValue::set(params.priority),
            ..Default::default()
        }
        .insert(db)
        .await?;

        Ok(tax_rule)
    }

    /// Deletes the tax rule
    ///
    /// # Errors
    ///
    /// When could not delete the tax rule from the DB
    pub async fn delete(self, db: &DatabaseConnection) -> ModelResult<DeleteResult> {
        let model: tax_rules::ActiveModel = self.into();
        Ok(model.delete(db).await?)
    }
}

impl ActiveModel {
    /// Updates the tax rule's based type
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_based(
        mut self,
        db: &DatabaseConnection,
        based: Based,
    ) -> ModelResult<Model> {
        self.based = ActiveValue::set(based);
        Ok(self.update(db).await?)
    }

    /// Updates the tax rule's priority
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_priority(
        mut self,
        db: &DatabaseConnection,
        priority: i32,
    ) -> ModelResult<Model> {
        self.priority = ActiveValue::set(priority);
        Ok(self.update(db).await?)
    }
}
